package util

import (
	"encoding/json"
	"fmt"
	"strconv"
)

type AnyInt int

func (m *AnyInt) UnmarshalJSON(data []byte) error {
	var a any
	if err := json.Unmarshal(data, &a); err != nil {
		return err
	}

	var v int
	switch assertVal := a.(type) {
	case string:
		if parsed, err := strconv.Atoi(assertVal); err == nil {
			v = parsed
		} else {
			v = 0
		}
	case bool:
		v = 1
		if !assertVal {
			v = 0
		}
	case float64: // JSON numbers are floats
		v = int(assertVal)
	case nil:
		v = 0
	default:
		v = 0
	}

	*m = AnyInt(v)
	return nil
}

type AnyString string

func (m *AnyString) UnmarshalJSON(data []byte) error {
	var a any
	if err := json.Unmarshal(data, &a); err != nil {
		return err
	}

	var v string
	switch assertVal := a.(type) {
	case string:
		v = assertVal
	case bool, float64:
		v = fmt.Sprintf("%v", assertVal)
	case nil:
		v = ""
	default:
		v = ""
	}

	*m = AnyString(v)
	return nil
}

type AnyBool bool

func (m *AnyBool) UnmarshalJSON(data []byte) error {
	var a any
	if err := json.Unmarshal(data, &a); err != nil {
		return err
	}

	var v bool
	switch assertVal := a.(type) {
	case bool:
		v = assertVal
	case string:
		v = assertVal != ""
	case float64:
		v = assertVal != 0
	case nil:
		v = false
	default:
		v = false
	}

	*m = AnyBool(v)
	return nil
}

type AnyFloat float64

func (m *AnyFloat) UnmarshalJSON(data []byte) error {
	var a interface{}
	if err := json.Unmarshal(data, &a); err != nil {
		return err
	}
	var v float64
	switch assertVal := a.(type) {
	case string:
		if parsed, err := strconv.ParseFloat(assertVal, 64); err == nil {
			v = parsed
		} else {
			v = 0.0 // 转换失败，设置为 0.0
		}
	case float64:
		v = assertVal
	case bool:
		if assertVal {
			v = 1.0
		} else {
			v = 0.0
		}
	case nil:
		v = 0.0
	default:
		v = 0.0
	}

	*m = AnyFloat(v)
	return nil
}
